import router from "./router";
import store from "./store";
import { Message } from "element-ui";
import NProgress from "nprogress"; // progress bar
import "nprogress/nprogress.css"; // progress bar style
import { getToken } from "@/utils/auth"; // get token from cookie
import getPageTitle from "@/utils/get-page-title";
import Layout from "@/layout";

const imports = require("@/router/import_" + process.env.NODE_ENV);
NProgress.configure({ showSpinner: false }); // NProgress Configuration

const whiteList = ["/login"]; // no redirect whitelist
router.beforeEach(async (to, from, next) => {
  // start progress bar
  NProgress.start();

  // set page title
  document.title = getPageTitle(to.meta.title);

  // determine whether the user has logged in
  const hasToken = getToken();
  if (hasToken) {
    if (to.path === "/login") {
      // if is logged in, redirect to the home page
      next({ path: "/" });
      NProgress.done();
    } else {
      const hasGetUserInfo = store.getters.name;
      if (hasGetUserInfo) {
        next();
      } else {
        try {
          // get user info
          await store.dispatch("user/getInfos");
          await store.dispatch("user/getrole");
          await store.dispatch("user/getInfomation");
          if (store.getters.menus.length < 1) {
            global.antRoute = [];
            next();
          }
          // next()
          // 1.过滤路由
          const menus = filterAsyncRouter(store.getters.menus);
          menus.forEach((e) => {
            if (e.children) {
              e.children.forEach((f) => {
                Object.assign(f, {
                  meta: {
                    icon: f.icon,
                    title: f.name
                  },
                });
                f.name = "";
              });
            }
            Object.assign(e, {
              meta: {
                icon: e.icon,
                title: e.name
              },
              alwaysShow: true,
              redirect:e.path,
            }); 
            e.name = "";
          });
          for (let i = 0; i < menus.length; i++) {
            if (menus[i].path == "/dashboard") {
              menus[i].path = "/";
              let obj = {
                path: "/myuser", 
                component: Layout,
                redirect: "/myuser",
                children: [
                  {
                    path: "myuser",
                    name: "myuser",
                    component: () => import("@/views/myuser/index"),
                    meta: { title: "个人中心", icon: "dashboard"},
                  },
                ],
              };
              menus.push(obj);
              break;
            } else {
              let obj = {
                path: "/",
                component: Layout,
                redirect: "/myuser",
                children: [
                  {
                    path: "myuser",
                    name: "myuser",
                    component: () => import("@/views/myuser/index"),
                    meta: { title: "个人中心", icon: "dashboard"},
                  },
                ],
                
              };
              menus.push(obj);
              break;
            }
          }
          menus.push({
            path: "*",
            redirect: "/404",
          });
          //2.将*直接 加载到动态路由，避免404
        
          //动态添加路由
          router.addRoutes(menus);
          //将路由数据传递给全局变量
          global.antRouter = menus;
          next({ ...to, replace: true });
        } catch (error) {
          // remove token and go to login page to re-login
          await store.dispatch("user/resetToken");
          Message.error({
            message: error || "出现错误，请稍后再试",
          });
          next(`/login?redirect=${to.path}`);
          NProgress.done();
        }
      }
    }
  } else {
    /* has no token*/

    if (whiteList.indexOf(to.path) !== -1) {
      // in the free login whitelist, go directly
      next();
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.path}`);
      NProgress.done();
    }
  }
});

// 遍历后台传来的路由字符串，转换为组件对象
function filterAsyncRouter(asyncRouterMap) {
  const accessedRouters = asyncRouterMap.filter((route) => {
    if (route.component) {
      if (route.component === "Layout") {
        route.component = Layout;
      } else {
        route.component = imports(route.component); // 导入组件
      }
    }
    if (route.children && route.children.length) {
      route.children = filterAsyncRouter(route.children);
    }
    return true;
  });

  return accessedRouters;
}

router.afterEach(() => {
  // finish progress bar
  NProgress.done();
});
